<!--
时间选择器
v1.0.0
-->

<template>
  <div class="sh-time">
    <sh-picker :id="id" v-model="picker_val"
               @scroll="pickerScroll"
               :width_ratio="[4,1,2,1,2,2,1,2]"
               :is_show.sync="c_show"
               :data="picker_data">
    </sh-picker>
  </div>
</template>
<style>
  .sh-time {
    position: fixed;
    z-index: 10000;
  }

  .sh-time .picker_list:nth-child(1) {
    margin-left: 1rem;
  }

  .sh-time .picker_list:nth-child(5) {
    margin-right: 2rem;
  }

  .sh-time .picker_list:nth-child(8) {
    margin-right: 1rem;
  }
</style>
<script>
  export default {
    name: 'sh-time',
    props: {
      id: String,
      value: String,
      show: Boolean,
      range: Array,//时间范围数组，默认前后一年，['2017-01-01 00:00:00','2019-01-01 00:00:00']
      type: String,//日期选择器类型，TIME/空：时间选择，DATE：日期选择（暂不支持）
    },
    data() {
      return {
        c_range: undefined,
        c_show: false,
        c_val: "",
        show_picker: true,
        picker_val: [],
        picker_data: [],
      }
    },
    beforeMount: function () {

    },
    mounted: function () {
      this.c_range = this.range;
      if (this.c_range === undefined) {
        this.c_range = [];
        let cur = new Date();
        cur.setFullYear(cur.getFullYear() - 1);
        this.c_range[0] = this.formatDate(cur, 'yyyy-MM-dd') + ' 00:00';
        cur.setFullYear(cur.getFullYear() + 2);
        this.c_range[1] = this.formatDate(cur, 'yyyy-MM-dd') + ' 23:59';
      } else {
        if (!this.c_range instanceof Array || this.c_range.length !== 2) {
          console.error('range范围必须是一个两位的数组');
          return null;
        }
      }
      this.c_val = this.value;
      if (!this.c_val) {
        let cur = new Date();
        this.c_val = this.formatDate(cur, 'yyyy-MM-dd hh:mm');
      }
      this.c_show = this.show;

      this.initPickerData();
      this.sycPickerVal();
    },
    methods: {
      initPickerData() {
        let cur = new Date();
        cur.setSeconds(0);
        cur.setMinutes(0);
        cur.setHours(0);
        let years = [];
        let months = [];
        let days = [];
        let hours = [];
        let minutes = [];

        let minYear = parseInt(this.c_range[0].split(' ')[0].split('-')[0]);
        let maxYear = parseInt(this.c_range[1].split(' ')[0].split('-')[0]);
        for (let year = minYear;
             year <= maxYear;
             year++) {
          years.push("" + year);
        }

        for (let i = 1; i <= 12; i++) {
          let val = i < 10 ? ("0" + i) : ("" + i);
          months.push(val);
        }

        let max_day = this.getMonthMaxDay(cur);
        for (let i = 1; i <= max_day; i++) {
          let val = i < 10 ? ("0" + i) : ("" + i);
          days.push(val);
        }

        for (let i = 0; i <= 23; i++) {
          let val = i < 10 ? ("0" + i) : ("" + i);
          hours.push(val);
        }
        for (let i = 0; i <= 59; i++) {
          let val = i < 10 ? ("0" + i) : ("" + i);
          minutes.push(val);
        }

        this.picker_data = [years, ['-'], months, ['-'], days, hours, [':'], minutes];

      },
      sycPickerVal() {
        let date = this.c_val.split(' ')[0];
        let time = this.c_val.split(' ')[1];
        let result = [];
        result.push(date.split('-')[0]);
        result.push("-");
        result.push(date.split('-')[1]);
        result.push("-");
        result.push(date.split('-')[2]);
        result.push(time.split(':')[0]);
        result.push(":");
        result.push(time.split(':')[1]);

        this.picker_val = result;
        this.$emit("input", this.c_val);
      },
      pickerScroll(val) {
        console.log(val);
        let max_day = this.getMonthMaxDay(`${val[0]}/${val[2]}/1`);
        if (this.picker_val[4] > max_day) {
          this.picker_val.splice(4, 1, max_day);
        }
        let days = [];
        for (let i = 1; i <= max_day; i++) {
          let val = i < 10 ? ("0" + i) : ("" + i);
          days.push(val);
        }
        this.picker_data[4] = days;

        this.c_val = `${this.picker_val[0]}-${this.picker_val[2]}-${this.picker_val[4]} ${this.picker_val[5]}:${this.picker_val[7]}`;
        this.$emit("input", this.c_val);
      },
      // 获取当月最大天数
      getMonthMaxDay(date_val) {
        let date = new Date(date_val);
        date.setDate(1);
        date.setMonth(date.getMonth() + 1);
        date.setDate(date.getDate() - 1);
        return date.getDate();
      },
      // 格式化日期
      formatDate(date, fmt) {
        let o = {
          "M+": date.getMonth() + 1, //月份
          "d+": date.getDate(), //日
          "h+": date.getHours(), //小时
          "m+": date.getMinutes(), //分
          "s+": date.getSeconds(), //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (let k in o)
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
      },

    },
    watch: {
      show() {
        this.c_show = this.show;
      },
      c_show() {
        this.$emit("update:show", this.c_show);
      },
      /*c_val() {
        this.$emit("input", this.c_val);
      }*/
    },
  };
</script>
